#include "minunit.h"
#include "../include/encrypt.h"
#include "../include/decrypt.h"
#include "../include/utils.h"

int tests_run = 0;

static char *test_cipher_context() {
    CipherContext *ctx = create_cipher_context("test_password");
    mu_assert("CipherContext creation failed", ctx != NULL);
    mu_assert("Password mismatch", strcmp(ctx->password, "test_password") == 0);
    free_cipher_context(ctx);
    return NULL;
}

static char *test_encryption_decryption() {
    // Test encryption and decryption process
    const char *input_file = "test_input.txt";
    const char *encrypted_file = "test_encrypted.bin";
    const char *decrypted_file = "test_decrypted.txt";

    FILE *fp = fopen(input_file, "wb");
    fwrite("Hello, World!", 1, strlen("Hello, World!"), fp);
    fclose(fp);

    CipherContext *ctx = create_cipher_context("test_password");
    int encrypt_result = encrypt_file(input_file, encrypted_file, ctx);
    mu_assert("Encryption failed", encrypt_result == 0);

    int decrypt_result = decrypt_file(encrypted_file, decrypted_file, ctx);
    mu_assert("Decryption failed", decrypt_result == 0);

    FILE *in = fopen(input_file, "rb");
    FILE *out = fopen(decrypted_file, "rb");

    fseek(in, 0, SEEK_END);
    fseek(out, 0, SEEK_END);
    long in_size = ftell(in);
    long out_size = ftell(out);
    rewind(in);
    rewind(out);

    mu_assert("File sizes do not match", in_size == out_size);

    char *in_data = malloc(in_size);
    char *out_data = malloc(out_size);

    fread(in_data, 1, in_size, in);
    fread(out_data, 1, out_size, out);

    mu_assert("Decrypted content does not match original", memcmp(in_data, out_data, in_size) == 0);

    free(in_data);
    free(out_data);
    fclose(in);
    fclose(out);
    free_cipher_context(ctx);

    return NULL;
}

static char *all_tests() {
    mu_run_test(test_cipher_context);
    mu_run_test(test_encryption_decryption);
    return NULL;
}

RUN_TESTS(all_tests)